package mysql

import (
	"encoding/json"
	"errors"
	"fmt"
	"my_chat/model"
	"sort"
)

func GetUserComids(userId int64) (comIds []int64, err error) {
	contacts := make([]model.Contact, 0)
	comIds = make([]int64, 0)
	err = db.Table("contacts").Select("dstobj").Where("ownerid = ? AND cate = ?", userId, 2).Find(&contacts).Error
	if err!=nil{
		fmt.Println("e", comIds)
		return comIds, err
	}
	for _,v := range contacts {
		comIds = append(comIds, v.Dstobj)
	}
	return comIds, nil
}

func SaveMessage(data []byte) (err error) {
	msg := model.Message{}
	err = json.Unmarshal(data, &msg)
	if err!=nil{
		return errors.New("序列化信息出错")
	}
	if msg.Content == "ping"{
		fmt.Println("心跳检测")
		return nil
	}
	err = db.Create(&msg).Error
	if err!=nil{
		fmt.Println("保存聊天信息出错", err.Error())
		return err
	}
	return nil
}

func GetMessages(userId int64, dstobj int64, cmd int64) (data interface{}, err error) {
	var msgList model.Messages
	if cmd == 0{
		err = errors.New("缺少参数cmd")
		fmt.Println(err.Error())
		return nil, err
	}
	if cmd == 10{
		err = db.Preload("User").Limit(20).Order("id desc").Where(&model.Message{Userid: userId, Dstid: dstobj}).Or(&model.Message{Userid: dstobj, Dstid: userId}).Find(
			&msgList).Error
	} else {
		err = db.Preload("User").Where(&model.Message{Dstid: dstobj}).Find(
			&msgList).Error
	}
	sort.Sort(&msgList)
	if err!=nil{
		fmt.Println(err.Error())
		return nil, err
	}
	return msgList, nil
}

